import Vue from 'vue';

const transitionEndEventListener = (el) => {
  el.addEventListener('transitionend', function transitionEndHandler () {
    el._transitionEndHandler = transitionEndHandler;
    el.removeEventListener('transitionend', el._transitionEndHandler);
    el.remove();
  });
};

const DropList = {
  dropComponent: null,
  destroyDrop () {
    document.removeEventListener('click', document.clickHandlers);
    this.dropComponent.$destroy();
    this.dropComponent.$el.style.height = 0;
    transitionEndEventListener(this.dropComponent.$el);
  },
  createDrop (config) {
    let Drop = Vue.extend({
      template: `<ul class="lanaya-select__drop">
        <li class="lanaya-select__drop--item" v-for="(op, index) in options" 
        :key="index" 
        :class="hasSelectedClass(op)"
        @click="selectItem(op)">{{opLabel(op)}}</li>
      </ul>`,
      methods: {
        selectItem (op) {
          this.selectVm.selectedItem = op;
          this.selectedOption = op;
        }
      },
      computed: {
        hasSelectedClass () {
          return function (op) {
            return {
              'is-selected': this.selectedOption === op
            };
          };
        },
        opLabel () {
          return function (op) {
            return op[this.format.label];
          };
        }
      },
      data: function () {
        return {
          options: config.options,
          format: config.format,
          selectVm: config.vm,
          selectedOption: null,
          height: 0
        };
      },
      mounted () {
        let rectObj = this.selectVm.$el.getBoundingClientRect();
        this.$el.style.width = rectObj.width + 'px';
        this.$el.style.left = rectObj.left + 'px';
        this.$el.style.top = (rectObj.top + rectObj.height + 3) + 'px';
        let _this = this;
        this.selectedOption = this.selectVm.selectedItem;
        document.addEventListener('click', function clickComponentHandler (e) {
          document.clickHandlers = clickComponentHandler;
          if (!_this.selectVm.$el.contains(e.target)) {
            _this.selectVm.isDrop = false;
            document.removeEventListener('click', document.clickHandlers);
            _this.$destroy();
            _this.$el.style.height = 0;
            transitionEndEventListener(_this.$el);
          }
        });
      }
    });
    let component = new Drop().$mount();
    let $el = component.$el;
    this.dropComponent = component;
    document.body.appendChild($el);
    let height = $el.getBoundingClientRect().height;
    $el.style.height = 0;
    setTimeout(() => {
      $el.style.height = height + 'px';
    });
  }
};

export { DropList };
